package com.bjc.platform.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.bjc.platform.model.AdmOrg;
import com.bjc.platform.service.AdmOrgService;

public class BaseController {
	
	public static final String MESSAGES_KEY = "successMessages";
	public static final String ERRORS_MESSAGES_KEY = "errors";

	@Autowired
	private AdmOrgService admOrgService;

	/**
	 * Log variable for all child classes.
	 */
	protected final Log log = LogFactory.getLog(getClass());

	/**
	 * Common Exception handler
	 * 
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public void handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) {

		String accept = request.getHeader("Accept");
		try {
			if (accept == null || accept.contains("*/*") || accept.contains("application/json")) {
				response.setHeader("content-type", "text/plain;charset=UTF-8");
				response.getWriter().print(ex.getMessage());
			} else {

			}
		} catch (Exception e) {

		}
	}

	/**
	 * 获得用户能查看数据范围
	 * 
	 * @param orgType
	 * @param subTypes
	 * @return
	 */
	protected String getUserOperationIds(String orgType, String[] subTypes) {
		List<AdmOrg> orgs = this.admOrgService.queryUserOperationOrg(orgType, subTypes);
		StringBuilder ids = new StringBuilder();
		int num = orgs.size();
		int i = 0;
		for (AdmOrg org : orgs) {
			ids.append(org.getId());
			if (num > 1 && i != num - 1) {
				ids.append(",");
			}
			i++;
		}
		return ids.toString();
	}

	/**
	 * 获得用户能操作的数组
	 * 
	 * @param orgType
	 * @param subTypes
	 * @return
	 */
	protected List<AdmOrg> getUserOperationOrgs(String orgType, String[] subTypes) {
		return this.admOrgService.queryUserOperationOrg(orgType, subTypes);
	}
}
